#include "widget.h"
#include "music.h"

#include <QUrlQuery>
#include <QNetworkReply>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QThread>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    QAudioFormat format;
    format.setSampleRate(16000);//设置声音的采样频率
    format.setChannelCount(1);//设置单声道
    format.setSampleSize(16);//16位深
    format.setSampleType(QAudioFormat::SignedInt);
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setCodec("audio/pcm");

    recorder = new QAudioInput(format, this);

    player = new QAudioOutput(format, this);
    connect(player, &QAudioOutput::stateChanged, this, &Widget::play_state_slot);

    bds = new BaiduSpeech(this, "Vn8E99bVCBssmYxcy8I8lfGB", "nc7uqzcE9pc9AvuPKF5we8Zx4oM7pciR");
    connect(bds, &BaiduSpeech::doneASR, this, &Widget::asr_finished_slot);
    connect(bds, &BaiduSpeech::doneTTS, this, &Widget::tts_finished_slot);
    connect(bds,&BaiduSpeech::speech_error,this,&Widget::error_speech);
    client = new QNetworkAccessManager(this);
    connect(client, &QNetworkAccessManager::finished, this, &Widget::on_reply);
    music_player = new Music(this);
    asrbuf = new QBuffer;
    asrbuf->open(QIODevice::ReadWrite);
    recorder->start(asrbuf);

    time = new QTimer(this);
    time->start(3000);
    connect(time,&QTimer::timeout,this,&Widget::on_time);
}

Widget::~Widget()
{
}

void Widget::error_speech()
{
    bds->message() = "speech error";
}
void Widget::on_time()
{
    time->stop();
    if (recorder->state() == QAudio::ActiveState)
    {
        recorder->suspend();
        bds->doASR(asrbuf->data());
        asrbuf->reset();//清空已检测的声音数据，重新录音
    }
}

void Widget::asr_finished_slot()
{
    if (bds->message().size())
    {
        if(bds->message() == "睡觉去。")
        {
            this->close();
        }
        int res = music_unit(bds->message());
        if(res == 1)
        {
            return ;
        }
        QUrlQuery params;
        params.addQueryItem("cmd", "chat");
        params.addQueryItem("appid", "411acdb0b376cf45c4e5eeff9e33d61f");
        params.addQueryItem("userid", "houyuanhao");
        params.addQueryItem("text", bds->message());

        QNetworkRequest request(QUrl("http://idc.emotibot.com/api/ApiKey/openapi.php"));
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

        client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    }
    asrbuf->deleteLater();
}

void Widget::tts_finished_slot()
{
    if (!bds->audio().size())
    {
        return;
    }
    ttsbuf = new QBuffer;
    ttsbuf->open(QIODevice::ReadWrite);
    ttsbuf->write(bds->audio());
    ttsbuf->reset();
    player->start(ttsbuf);
}

void Widget::play_state_slot(QAudio::State s)
{
    if (s == QAudio::IdleState) {
        player->stop();
        ttsbuf->close();
        ttsbuf->deleteLater();
        this->close();
    }
}

void Widget::on_reply(QNetworkReply* reply)
{
    QString msg = "";
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    if (json["return"].toInt()) {
        msg = "speech error";
    }
    else {
        QJsonArray array = json["data"].toArray();
        for(int i = 0; i < array.size(); i++)
        {
            if (array[i].toObject()["type"] == "text") {
                msg += array[i].toObject()["value"].toString();
            }
        }
    }
    bds->doTTS(msg);
    reply->deleteLater();
}

int Widget::judge(QString str)
{
    if(str[0] == "播"&&str[1] == "放")
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

int Widget::music_unit(QString str)
{
    if(str == "停止。")
    {
        music_player->stop_music();
    }
    if(str == "暂停。")
    {
        music_player->pause_music();
    }
    if(str == "继续。")
    {
        music_player->append_music();
    }
    if(str == "增大音量。")
    {
        music_player->voice_up();
    }
    if(str == "减小音量。")
    {
        music_player->voice_down();
    }
    if(judge(str))
    {
        QString name = "";

        int size = str.size();
        int i = 0,j = 0;

        for(i = 0;i<size;i++)
        {
            if(str[i] == "放")
            {
                for(j = i+1;j<size;j++)
                {
                    if(str[j] == "。")
                    {
                        goto end;
                    }
                    name += str[j];
                }
            }
        }
end:
        qDebug()<<name<<endl;
        int res = music_player->play_music(name);
        if(res == 0)
        {
            return 0;
        }
        connect(music_player,&Music::play_finished,this,&Widget::music_end);
        return 1;
    }
    return 0;
}
void Widget:: music_end()
{
    this->close();
}

